﻿using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using SJ.Platform.Common;
using SJ.Platform.EFCore.Model;
using SJ.Platform.EFCore.Model.OrgManager;
using SJ.Platform.Extend.ModelExtend;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace SJ.Platform.EFCore.DBOperation.DBOperation.MySQL.Sys
{
    /// <summary>
    /// 组织机构操作类
    /// </summary>
    public class Sys_OrgHandle
    {
        private readonly SJDBContext _context;

        public Sys_OrgHandle(SJDBContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<bool> CreateAsync(SysOrg entity)
        {
            try
            {
                _context.SysOrgs.Add(entity);
                await _context.SaveChangesAsync();
                return true;
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Sys_OrgHandle=>Create", ex);
                return false;
            }
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<bool> UpdateAsync(SysOrg entity)
        {
            try
            {
                _context.Entry(entity).State = EntityState.Modified;
                await _context.SaveChangesAsync();
                return true;
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Sys_OrgHandle=>Update", ex);
                return false;
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool Delete(SysOrg entity)
        {
            try
            {
                _context.SysOrgs.Remove(entity);
                return _context.SaveChanges() > 0;
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Sys_OrgHandle=>Delete", ex);
                return false;
            }
        }

        /// <summary>
        /// 根据主键删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<bool> DeleteByIdAsync(string id)
        {
            try
            {
                var entity = _context.SysOrgs.Find(id);
                if (entity != null)
                {
                    _context.SysOrgs.Remove(entity);
                    await _context.SaveChangesAsync();
                    return true;
                }
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Sys_OrgHandle=>DeleteById", ex);
            }
            return false;
        }

        /// <summary>
        /// 根据ID获取实体
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<SysOrg> GetEntityByIdAsync(string id)
        {
            try
            {
                return await _context.SysOrgs.FindAsync(id);
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Sys_OrgHandle=>GetEntityById", ex);
            }
            return null;
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="pageNumber"></param>
        /// <param name="pageSize"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public List<SysOrg> GetAll(int pageNumber, int pageSize, ref int count, Expression<Func<SysOrg, bool>> condition = null)
        {
            try
            {
                var query = _context.SysOrgs.AsQueryable();

                // 如果提供了查询条件，则应用它
                if (condition != null)
                {
                    query = query.Where(condition);
                }
                count = query.Count();
                // 应用分页
                var skip = (pageNumber - 1) * pageSize;
                query = query.Skip(skip).Take(pageSize);

                // 执行查询并返回结果
                return query.ToList();
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Sys_OrgHandle=>GetAll  page", ex);
            }
            return null;
        }

        /// <summary>
        /// 分页获取所有组织机构
        /// </summary>
        /// <param name="pageNumber"></param>
        /// <param name="pageSize"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public async Task<(List<SysOrg> orgs, int count)> GetAllAsync(int pageNumber, int pageSize, Expression<Func<SysOrg, bool>> condition = null)
        {
            // 查询条件
            IQueryable<SysOrg> query = _context.SysOrgs;

            // 应用条件表达式（如果提供了条件）
            if (condition != null)
            {
                query = query.Where(condition);

            }

            //总条数
            int count = await query.CountAsync();

            // 应用分页
            var skip = (pageNumber - 1) * pageSize;
            query = query.Skip(skip).Take(pageSize);

            // 执行查询并返回结果
            var orgs = await query.ToListAsync();

            return (orgs, count);
        }

        /// <summary>
        /// 分页获取所有组织机构
        /// </summary>
        /// <param name="pageNumber"></param>
        /// <param name="pageSize"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public async Task<(List<SysOrgExtend> orgs, int count)> GetAllAndChildAsync(int pageNumber, int pageSize, SysOrg condition)
        {
            List<SysOrg> orgList = _context.SysOrgs.FromSqlRaw(@"WITH RECURSIVE OrgHierarchy AS (
	                                                            SELECT Id,OrgName,PId,OrgType,Mark,AddTime,AddUserId,EditTime,EditUserId 
		                                                            FROM sys_org 
		                                                            WHERE Id = '" + condition.Id + @"' UNION ALL
		                                                            SELECT c.Id,c.OrgName,c.PId,c.OrgType,c.Mark,c.AddTime,c.AddUserId,c.EditTime,c.EditUserId
			                                                            FROM sys_org c INNER JOIN OrgHierarchy p ON c.PId = p.Id )
                                                                SELECT * FROM OrgHierarchy;").ToList();
            if (orgList != null && orgList.Count > 0)
            {
                var cOrgList = orgList.Where(o => (!string.IsNullOrWhiteSpace(condition.OrgName) ? o.OrgName.Contains(condition.OrgName) : true) && (condition.OrgType != null && condition.OrgType != 0 ? o.OrgType == condition.OrgType : true));
                if (cOrgList != null && cOrgList.Count() > 0)
                {
                    orgList = cOrgList.ToList();
                }
                else
                    orgList = new List<SysOrg>();
            }

            //总条数
            int count = orgList.Count();

            // 应用分页
            var skip = (pageNumber - 1) * pageSize;
            var orgListPage = orgList.Skip(skip).Take(pageSize).ToList();

            // 将 SysOrg 映射到 SysOrgExtend
            List<SysOrgExtend> orgExtendList = orgListPage.Select(org => new SysOrgExtend
            {
                Id = org.Id,
                OrgName = org.OrgName,
                Pid = org.Pid,
                OrgType = org.OrgType,
                Mark = org.Mark,
                AddTime = org.AddTime,
                AddUserId = org.AddUserId,
                EditTime = org.EditTime,
                EditUserId = org.EditUserId,
                PName = !string.IsNullOrWhiteSpace(org.Pid) ? orgList.Where(o => o.Id == org.Pid) != null && orgList.Where(o => o.Id == org.Pid).FirstOrDefault() != null ? orgList.Where(o => o.Id == org.Pid).FirstOrDefault().OrgName : "" : "",
                OrgTypeCn = org.OrgType == 1 ? "公司" : "部门", // 根据 OrgType 计算
            }).ToList();

            //有Pid，但是pName为空的处理
            List<SysOrgExtend> orgNoPNameList = orgExtendList.Where(o => !string.IsNullOrWhiteSpace(o.Pid) && string.IsNullOrWhiteSpace(o.PName)).ToList();
            if (orgNoPNameList != null && orgNoPNameList.Count() > 0)
            {
                List<string> pIdList = new List<string>();
                foreach (SysOrgExtend org in orgNoPNameList)
                {
                    if (!pIdList.Contains(org.Pid))
                    {
                        pIdList.Add(org.Pid);
                    }
                }
                List<SysOrg> pOrgList = _context.SysOrgs.FromSqlRaw("select Id,OrgName,PId,OrgType,Mark,AddTime,AddUserId,EditTime,EditUserId FROM sys_org where Id in ('" + string.Join("','", pIdList.ToArray()) + "')").ToList();

                foreach (SysOrgExtend org in orgNoPNameList)
                {
                    org.PName = pOrgList.Find(o => o.Id == org.Pid) != null ? pOrgList.Find(o => o.Id == org.Pid).OrgName : "";
                }
            }

            var orgs = orgExtendList;
            return (orgs, count);
        }

        /// <summary>
        /// 获取所有组织机构
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        public async Task<List<SysOrg>> GetAllAsync(Expression<Func<SysOrg, bool>> condition = null)
        {
            try
            {
                IQueryable<SysOrg> query = _context.SysOrgs;

                // 如果提供了查询条件，则应用它
                if (condition != null)
                {
                    query = query.Where(condition);
                }

                // 执行查询并返回结果
                return await query.ToListAsync();
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Sys_OrgHandle=>GetAll", ex);
            }
            return null;
        }

        /// <summary>
        /// 根据组织机构ID获取自身及其子级
        /// </summary>
        /// <param name="orgId"></param>
        /// <returns></returns>
        public async Task<List<SysOrgExtend>> GetAllByOrgId(string orgId)
        {
            try
            {
                var entity = _context.SysOrgs.FindAsync(orgId).Result;
                if (entity != null)
                {
                    List<SysOrg> orgList = new List<SysOrg> { entity };

                    List<SysOrgExtend> sysOrgExtendList = new List<SysOrgExtend>();

                    BuildChild(sysOrgExtendList, orgList);

                    return sysOrgExtendList;
                }
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Sys_OrgHandle=>GetAllByOrgId", ex);
            }
            return null;
        }
        /// <summary>
        /// 根据用户ID获取组织机构
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<List<SysOrgExtend>> GetAllByUserId(string userId)
        {
            try
            {
                var query = from org in _context.SysOrgs
                            join user in _context.SysUsers on org.Id equals user.OrgId
                            where user.Id == userId
                            select org;

                var orgList = await query.ToListAsync();

                List<SysOrgExtend> sysOrgExtendList = new List<SysOrgExtend>();

                BuildChild(sysOrgExtendList, orgList);

                return sysOrgExtendList;
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Sys_OrgHandle=>GetAllByUserId", ex);
            }
            return null;
        }
        /// <summary>
        /// 递归生成子级
        /// </summary>
        /// <param name="sysOrgExtendList"></param>
        /// <param name="orgList"></param>
        private void BuildChild(List<SysOrgExtend> sysOrgExtendList, List<SysOrg> orgList)
        {
            try
            {
                if (orgList != null && orgList.Count > 0)
                {
                    foreach (var org in orgList)
                    {
                        SysOrgExtend sysOrgExtend = new SysOrgExtend();
                        sysOrgExtend.Id = org.Id;
                        sysOrgExtend.OrgName = org.OrgName;
                        sysOrgExtend.Pid = org.Pid;
                        sysOrgExtend.Mark = org.Mark;
                        sysOrgExtend.AddUserId = org.AddUserId;
                        sysOrgExtend.AddTime = org.AddTime;
                        sysOrgExtend.EditTime = org.EditTime;
                        sysOrgExtend.EditUserId = org.EditUserId;

                        var childOrgList = GetAllAsync(o => o.Pid == org.Id).Result;
                        if (childOrgList != null && childOrgList.Count > 0)
                        {
                            if (sysOrgExtend.childOrgList == null)
                            {
                                sysOrgExtend.childOrgList = new List<SysOrgExtend>();
                            }
                            BuildChild(sysOrgExtend.childOrgList, childOrgList);
                        }

                        sysOrgExtendList.Add(sysOrgExtend);
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Sys_OrgHandle=>BuildChild", ex);
            }
        }
    }
}